import 'package:camera/camera.dart';
import 'package:image/image.dart' as img;

class ImageUtil {
  static img.Image convertYUV420ToImage(CameraImage cameraImage) {
    final width = cameraImage.width;
    final height = cameraImage.height;

    final yRowStride = cameraImage.planes[0].bytesPerRow;
    final uvRowStride = cameraImage.planes[1].bytesPerRow;
    final uvPixelStride = cameraImage.planes[1].bytesPerPixel ?? 0;

    final image = img.Image(width: width, height: height);

    for (var w = 0; w < width; w++) {
      for (var h = 0; h < height; h++) {
        final uvIndex =
            uvPixelStride * (w / 2).floor() + uvRowStride * (h / 2).floor();
        final yIndex = h * yRowStride + w;

        final y = cameraImage.planes[0].bytes[yIndex];
        final u = cameraImage.planes[1].bytes[uvIndex];
        var v = 0;
        if (cameraImage.planes.length == 3) {
          v = cameraImage.planes[2].bytes[uvIndex];
        }

        image.data?.setPixel(w, h, yuv2rgb(y, u, v));
      }
    }
    return image;
  }

  static img.Color yuv2rgb(int y, int u, int v) {
    // YUV 转 RGB 公式
    var r = (y + 1.402 * (v - 128)).round();
    var g = (y - 0.344136 * (u - 128) - 0.714136 * (v - 128)).round();
    var b = (y + 1.772 * (u - 128)).round();
    // 将 RGB 值限制在 0 到 255 之间
    r = r.clamp(0, 255);
    g = g.clamp(0, 255);
    b = b.clamp(0, 255);

    return img.ColorRgb8(r, g, b);
  }

  static LuxTemp calculateAverageTemperature(img.Image image) {
    double totalTemperature = 0.0;
    int totalPixels = 0;
    double totalLuminance = 0.0;
    for (int y = 0; y < image.height; y++) {
      for (int x = 0; x < image.width; x++) {
        img.Pixel pixel = image.getPixel(x, y);

        totalTemperature += (1000 /
            ((0.0402 * pixel.r) +
                (0.0193 * pixel.g) +
                (0.0322 * pixel.b) +
                4.67));
        totalLuminance += pixel.luminance.toDouble();
        totalPixels++;
      }
    }
    double averageTemperature = totalTemperature / totalPixels;
    double averageLuminance = totalLuminance / totalPixels;
    return LuxTemp(lux: averageLuminance, temp: averageTemperature);
  }
}

class LuxTemp {
  final double lux;
  final double temp;
  LuxTemp({required this.lux, required this.temp});
}
